package controller

import (
	"StrayAnimals/internal/service"
	"github.com/gin-gonic/gin"
)

func UpdateAnimalMsg(c *gin.Context) {
	var userInput struct {
		ID          string `json:"id"`
		Name        string `json:"name"`
		Age         int    `json:"age"`
		Type        string `json:"type"`
		Information string `json:"information"`
		Picture1    string `json:"picture1"`
		Picture2    string `json:"picture2"`
		Picture3    string `json:"picture3"`
		UploadedAt  string `json:"uploadedAt"`
		IsAdopted   bool   `json:"isAdopted"`
	}

	if err := c.ShouldBindJSON(&userInput); err != nil {
		c.JSON(400, gin.H{
			"code":    400,
			"message": "请求参数错误；" + err.Error(),
		})
		return
	}

	animal, err := service.GetAnimalById(userInput.ID)
	if err != nil {
		c.JSON(403, gin.H{
			"code":    403,
			"message": "数据库中没有该动物" + err.Error(),
		})
		return
	}

	if userInput.Name != "" {
		animal.Name = userInput.Name
	}
	if userInput.Age != animal.Age {
		animal.Age = userInput.Age
	}
	if userInput.Type != "" {
		animal.Type = userInput.Type
	}
	if userInput.Information != "" {
		animal.Information = userInput.Information
	}
	if userInput.Picture1 != "" {
		animal.Picture1 = userInput.Picture1
	}
	if userInput.Picture2 != "" {
		animal.Picture2 = userInput.Picture2
	}
	if userInput.Picture3 != "" {
		animal.Picture3 = userInput.Picture3
	}
	if userInput.UploadedAt != "" {
		animal.UploadedAt = userInput.UploadedAt
	}
	if userInput.IsAdopted != animal.IsAdopted {
		animal.IsAdopted = userInput.IsAdopted
	}

	if err := service.UpdateAnimal(animal); err != nil {
		c.JSON(500, gin.H{
			"code":    501,
			"message": "系统错误，修改动物信息失败，请稍后再试；" + err.Error(),
		})
		return
	}

	c.JSON(200, gin.H{
		"code":    200,
		"message": "修改动物信息成功",
	})
}
